import { getApiUrl, getAuth, handleUnauthorized } from "./common";
import { IPSet, IPSetInfo, IPSetRule } from "./types";

/**
 * 获取IPSet 列表
 * @returns
 */
export async function getIPSets(): Promise<Record<string, IPSet> | null> {
  try {
    const auth = getAuth();
    if (!auth) {
      return null;
    }
    const url = getApiUrl("/ipset/list");
    const res = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: auth,
      },
    });
    if (res.status === 401) {
      handleUnauthorized(url);
    }
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    const data = await res.json();

    return data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

/**
 * 获取IPSet 详情
 * @returns
 */
export async function getIPSetInfo(setname: string): Promise<IPSetInfo | null> {
  try {
    if (!setname) {
      return null;
    }
    const auth = getAuth();
    if (!auth) {
      return null;
    }
    const url = getApiUrl(`/ipset/${setname}/info`);
    const res = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: auth,
      },
    });
    if (res.status === 401) {
      handleUnauthorized(url);
    }
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    const data = await res.json();

    return data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

/**
 * 删除IPSet 规则
 * @returns
 */
export async function deleteIPSetRule(
  setname: string,
  rule: IPSetRule
): Promise<boolean> {
  try {
    if (!setname) {
      return false;
    }
    const auth = getAuth();
    if (!auth) {
      return false;
    }
    const url = getApiUrl(`/ipset/${setname}/del`);
    const res = await fetch(url, {
      method: "DELETE",
      headers: {
        Authorization: auth,
      },
      body: JSON.stringify(rule),
    });
    if (res.status === 401) {
      handleUnauthorized(url);
    }
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    return true;
  } catch (err) {
    console.error(err);
  }
  return false;
}

function isValidIPv4(ipAddress: string): boolean {
  const regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  return regex.test(ipAddress);
}

/**
 * 校验备注 不允许存在 |\$>&*;!`"'
 * @param remark
 * @returns
 */
function isValidRemark(remark: string): boolean {
  const regex = /[|\\$>&*;!`"']/;
  return !regex.test(remark);
}
/**
 * 校验规则
 * @param rule
 * @returns 错误
 */
export function checkRule(rule: IPSetRule): string {
  if (!isValidIPv4(rule.ip)) {
    return `IP: ${rule.ip} 非ipv4地址`;
  }
  if (rule.timeout < 0) {
    return `timeout: ${rule.timeout} 必须为正整数`;
  }
  // if (!isValidRemark(rule.remarks)) {
  //   return "备注不允许存在 |\\$>&*;!`\"'";
  // }

  return "";
}


/**
 * 删除IPSet 规则
 * @returns
 */
export async function addIPSetRule(
  setname: string,
  rule: IPSetRule
): Promise<boolean> {
  try {
    if (!setname) {
      return false;
    }
    const auth = getAuth();
    if (!auth) {
      return false;
    }
    const url = getApiUrl(`/ipset/${setname}/add`);
    const res = await fetch(url, {
      method: "POST",
      headers: {
        Authorization: auth,
      },
      body: JSON.stringify(rule),
    });
    if (res.status === 401) {
      handleUnauthorized(url);
    }
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    return true;
  } catch (err) {
    console.error(err);
  }
  return false;
}